// pages/staff/list.js
const app = getApp()
const { request } = require("../../utils/request")

Page({
  data: {
    staffList: [],
    filteredList: [],
    searchKeyword: "",
    searchType: 0,
    searchTypes: ["按姓名", "按公司"],
    showDetail: false,
    currentStaff: null,
    currentStaffId: null,
    showEdit: false,
    editData: {},
    companyList: [], // 存储所有公司信息
    adminList: [], // 存储所选公司的管理员信息
  },

  onLoad() {
    this.loadStaffList()
  },

  // 加载员工列表
  loadStaffList() {
    wx.showLoading({ title: "加载中..." })
    request({
      url: `${app.globalData.baseUrl}/sadmin/admin_list/list`,
      method: "GET",
    })
      .then((res) => {
        console.log(res)
        if (res.statusCode === 200) {
          this.setData({
            staffList: res.data.data,
          })
        }
      })
      .catch(() => {
        wx.showToast({ title: "加载失败", icon: "none" })
      })
      .finally(() => {
        wx.hideLoading()
      })
  },

  searchStaffList() {
    wx.showLoading({ title: "加载中..." })
    request({
      url: `${app.globalData.baseUrl}/sadmin/admin_list/search_list?type=${this.data.searchType}&text=${this.data.searchKeyword}`,
      method: "GET",
    })
      .then((res) => {
        if (res.statusCode === 200) {
          this.setData({
            staffList: res.data.data,
          })
        }
      })
      .catch(() => {
        wx.showToast({ title: "加载失败", icon: "none" })
      })
      .finally(() => {
        wx.hideLoading()
      })
  },

  // 加载所有公司信息
  loadCompanyList() {
    request({
      url: `${app.globalData.baseUrl}/searchCompany`,
      method: "GET",
    })
      .then((res) => {
        console.log("公司列表:", res)
        if (res.statusCode === 200 && res.data.code === 1) {
          this.setData({
            companyList: res.data.data,
          })
        } else {
          wx.showToast({ title: "获取公司列表失败", icon: "none" })
        }
      })
      .catch(() => {
        wx.showToast({ title: "获取公司列表失败", icon: "none" })
      })
  },

  // 公司选择变更处理
  onCompanyChange(e) {
    const index = e.detail.value
    const selectedCompany = this.data.companyList[index]

    // 更新编辑数据中的公司信息
    this.setData({
      "editData.companyId": selectedCompany.id,
      "editData.companyName": selectedCompany.name,
    })
  },

  changeSearchType(e) {
    this.setData({
      searchType: e.detail.value,
      //filteredList: this.filterData(this.data.staffList)
    })
  },

  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value,
      //filteredList: this.filterData(this.data.staffList)
    })
  },

  filterData(list) {
    const keyword = this.data.searchKeyword.toLowerCase()
    return list.filter((item) => {
      const target = this.data.searchType === 0 ? item.name : item.company
      return target.toLowerCase().includes(keyword)
    })
  },

  handleFreeze(e) {
    console.log(e.currentTarget.dataset.id)
    this.updateStatus(e.currentTarget.dataset.id, 1)
  },

  handleUnfreeze(e) {
    console.log(e.currentTarget.dataset.id)
    this.updateStatus(e.currentTarget.dataset.id, 0)
  },

  updateStatus(id, status) {
    wx.showLoading({ title: "处理中..." })
    request({
      url: `${app.globalData.baseUrl}/sadmin/admin_list/status/${id}?status=${status}`,
      method: "PUT",
    })
      .then((res) => {
        if (res.statusCode === 200) {
          this.setData({
            staffList: res.data.data,
          })
          wx.showToast({ title: "操作成功" })
        }
      })
      .finally(() => {
        wx.hideLoading()
      })
  },

  handleRecharge(e) {
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: "积分充值",
      editable: true,
      success: (res) => {
        if (res.confirm && res.content) {
          const amount = Number.parseFloat(res.content)
          if (isNaN(amount)) {
            wx.showToast({ title: "请输入有效数字", icon: "none" })
            return
          }
          request({
            url: `${app.globalData.baseUrl}/sadmin/admin_list/point/${id}?amount=${amount}`,
            method: "PUT",
          }).then((res) => {
            if (res.statusCode === 200) {
              this.setData({
                staffList: res.data.data,
              })
            }
          })
        }
      },
    })
  },

  showEditDialog(e) {
    wx.showLoading({ title: "加载中..." })
    request({
      url: `${app.globalData.baseUrl}/sadmin/admin_list/detail/${e.currentTarget.dataset.id}`,
      method: "GET",
    })
      .then((res) => {
        if (res.statusCode === 200) {
          this.setData({
            showEdit: true,
            editData: res.data.data,
          })

          // 加载公司列表
          this.loadCompanyList()
        }
      })
      .catch(() => {
        wx.showToast({ title: "加载失败", icon: "none" })
      })
      .finally(() => {
        wx.hideLoading()
      })
  },

  onEditInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`editData.${field}`]: e.detail.value,
    })
  },

  saveStaffInfo() {
    // 验证必填字段
    if (!this.data.editData.companyId) {
      wx.showToast({
        title: "请选择公司",
        icon: "none",
      })
      return
    }
    if (!isValidPhoneNumber(this.data.editData.phone)) {
      wx.showToast({ title: "请输入有效电话号码", icon: "none" })
      return
    }
    if (!isValidIDCard(this.data.editData.idCard)) {
      wx.showToast({ title: "请输入有效身份证", icon: "none" })
      return
    }

    wx.showLoading({ title: "保存中..." })
    request({
      url: `${app.globalData.baseUrl}/sadmin/admin_list/update`,
      method: "PUT",
      data: this.data.editData,
    })
      .then((res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 1) {
            this.setData({
              staffList: res.data.data,
            })
            this.closeEdit()
            wx.showToast({ title: "保存成功" })
          } else if (res.data.code === 0) {
            wx.showToast({ title: `${res.data.msg}`, icon: "none" })
            return
          }
        }
      })
      .finally(() => {
        wx.hideLoading()
      })
  },

  handleDelete(e) {
    wx.showModal({
      title: "确认删除",
      content: "此操作不可恢复，确定删除？",
      success: (res) => {
        if (res.confirm) {
          request({
            url: `${app.globalData.baseUrl}/sadmin/admin_list/delete/${e.currentTarget.dataset.id}`,
            method: "DELETE",
          }).then((res) => {
            if (res.statusCode === 200) {
              this.setData({
                staffList: res.data.data,
              })
            }
          })
        }
      },
    })
  },

  showDetailDialog(e) {
    const staffId = e.currentTarget.dataset.id
    this.setData({
      showDetail: true,
      currentStaffId: staffId,
      currentStaff: null,
    })

    request({
      url: `${app.globalData.baseUrl}/staff/detail/${staffId}`,
      method: "GET",
    }).then((res) => {
      if (res.data.code === 200) {
        this.setData({ currentStaff: res.data.data })
      }
    })
  },

  closeEdit() {
    this.setData({
      showEdit: false,
      adminList: [],
      companyList: [],
    })
  },

  closeDetail() {
    this.setData({ showDetail: false })
  },
})

function isValidPhoneNumber(phone) {
  const regex = /^1[3-9]\d{9}$/
  return regex.test(phone)
}

function isValidIDCard(idCard) {
  // 1. 验证长度和格式
  const regex = /^(?:\d{15}|\d{17}[\dX])$/
  if (!regex.test(idCard)) {
    return false
  }

  // 2. 如果是18位，需进一步校验
  if (idCard.length === 18) {
    // 身份证前17位数字
    const weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    const code = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"]

    let sum = 0
    for (let i = 0; i < 17; i++) {
      sum += idCard[i] * weight[i]
    }

    const checkDigit = code[sum % 11] // 计算出的校验位
    return checkDigit === idCard[17].toUpperCase() // 比较校验位
  }

  return true // 15 位身份证合法
}
